package com.wusong.services;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class GoldMonitService extends Service {
	private final String _TAG = "BackGroudService";
	private ServiceBinder serviceBinder = new ServiceBinder();

	private MediaPlayer mMediaPlayer = null;

	private GoldDataGetor _getor = null;

	private int _intervalTime = 1;
	private final int _dataMessgaeId = 555;
	private boolean _enableMoniter = true;
	private boolean _enableRing = true;
	private boolean _isLess = true;
	private double monitValue = -1;
	private GoldMsg msg;

	Timer timer = null;
	TimerTask task = null;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 555:
				if (msg.obj != null) {
					onDataCome(msg.obj.toString());
				}
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return serviceBinder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		String dataFeedUrl = this.getResources()
				.getString(R.string.dataFeedUrl)
				+ String.valueOf(Math.random());
		_getor = new GoldDataGetor(dataFeedUrl);
		runWork();
		Log.v(_TAG, "service running");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
		}
		mMediaPlayer = null;
		if (timer != null) {
			timer.cancel();
		}
		timer = null;
		if (task != null) {
			task.cancel();
		}
		task = null;
	}

	public class ServiceBinder extends Binder implements IMoniteService {
		@Override
		public void setIfRun(boolean canRun) {
			// TODO Auto-generated method stub
			_enableMoniter = canRun;
			if (_enableMoniter) {
				runWork();
			}
			else{
				pauseWork();
			}
		}

		@Override
		public void setAlertFreq(int freq) {
			// TODO Auto-generated method stub
			_intervalTime = freq;
			runWork();
		}

		@Override
		public void setAlertValue(double alertValue) {
			// TODO Auto-generated method stub
			Log.v(_TAG, "setAlertValue");
			monitValue = alertValue;
			runWork();
		}

		@Override
		public void setMonitType(boolean isLess) {
			// TODO Auto-generated method stub
			_isLess = isLess;
			runWork();
		}

		@Override
		public String getMsg() {
			// TODO Auto-generated method stub
			if (msg != null) {
				return msg.getFormatString();
			}
			return null;
		}

		@Override
		public void stopRing() {
			stopAlarmRing();
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			runWork();
		}

		@Override
		public void stop() {
			// TODO Auto-generated method stub
			pauseWork();
		}

		@Override
		public void setIfRing(boolean canRing) {
			// TODO Auto-generated method stub
			_enableRing = canRing;
		}
	}

	protected void onDataCome(String data) {
		if (data == null || data.length() < 10)
			return;

		msg = GoldMsg.valueOf(data);

		double goldValue = Double.parseDouble(msg.midPrice);
		boolean isMatch = false;

		if (this._isLess) {
			isMatch = goldValue <= monitValue;
		} else {
			isMatch = goldValue >= monitValue;
		}
		if (isMatch) {
			// this.playAlarmRing();
			Log.v(_TAG, "ring");
		}

	}

	protected boolean checkIfRunTask() {
		return monitValue > 0 && this._enableMoniter;
	}

	protected void pauseWork() {
		if (timer == null) {
			return;
		}
		timer.cancel();
		timer = null;

	}

	protected void runWork() {
		if (!checkIfRunTask())
			return;

		if (task != null) {
			task.cancel();
			task = null;
		}
		task = new TimerTask() {
			public void run() {
				Log.v(_TAG, "runWork");
				Message message = new Message();
				message.what = _dataMessgaeId;
				String goldData = _getor.getData();
				message.obj = goldData;
				Log.v(_TAG, goldData);
				handler.sendMessage(message);
			}
		};

		timer = new Timer();
		timer.schedule(task, 1000, getIntervalTime());
		Log.v(_TAG, "timer start");

	}

	private long getIntervalTime() {
		return this._intervalTime * 60 * 1000;
	}

	private void playAlarmRing() {

		if (!this._enableRing)
			return;

		Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
		try {
			mMediaPlayer = new MediaPlayer();
			mMediaPlayer.setDataSource(this, alert);
			final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mMediaPlayer.setLooping(true);
				mMediaPlayer.prepare();
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mMediaPlayer.start();
	}

	private void stopAlarmRing() {
		this._enableRing = false;
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
		}
	}

}
